'use strict';

const Service = require('egg').Service;

class GoodsService extends Service {

  // 新增
  async create(payload) {
    const { app } = this;
    return await app.model.MallGoods.create(payload);
  }

  // 获取列表
  async getList(payload) {
    const { app } = this;
    const Op = app.Sequelize.Op;
    const { pageNum, pageSize, category_id, name, status, begin_pubdate, end_pubdate } = payload;
    const where = {};
    if (category_id) { where.category_id = category_id; }
    if (name) { where.name = name; }
    if (status) { where.status = status; }
    if (begin_pubdate && end_pubdate) {
      where.createdAt = { [Op.between]: [ begin_pubdate, end_pubdate ] };
    }// 查询这个字段-xx之间  }
    const { count, rows } = await app.model.MallGoods.findAndCountAll({
      where,
      order: [[ 'createdAt', 'desc' ]],
      offset: (pageNum - 1) * pageSize,
      limit: pageSize * 1,
    });
    return {
      pageNum,
      pageSize,
      total: count,
      list: rows,
    };
  }

  // 删除 软删除 和硬删除
  async del(id) {
    const { app, ctx } = this;
    if (ctx.url.search('off') !== -1) {
      return await app.model.MallGoods.destroy({ where: { id } });
    }
    return await app.model.MallGoods.destroy({ where: { id }, force: true });
  }


  // 上架
  async shelves(id) {
    const { app } = this;
    return await app.model.MallGoods.restore({ where: { id } });
  }
  // 修改
  async update(id, goods) {
    const { app } = this;
    return await app.model.MallGoods.update(goods, { where: { id } });
  }

}

module.exports = GoodsService;
